﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).
using System;
using System.Collections.Generic;
using System.Data;
#if NET20
using Z.Net.Legacy20;
#elif NET35 || NET40
using System.Linq;
#endif
using System.Linq;

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Sets internal data source expando object.
        /// </summary>
        public void SetInternalDataSourceExpandoObject()
        {
            List<object> datasource = DataSourceAsList;

            var dt = new DataTable();
            MappingList.ForEach(x => dt.Columns.Add(x.SourceColumn));

            bool isTypeAdded = false;

            foreach (object item in datasource)
            {
                // ExpandoObject mapping
                var dict = (IDictionary<string, object>) item;

                // Get keys to map by ExpandoObject

                var keys = dict.Keys.Where(x => dt.Columns.Contains(x)).ToList();

                
                

                // if it's the first row, ADD DataTable Column Type
                if (!isTypeAdded)
                {
                    isTypeAdded = true;

                    foreach (string key in keys)
                    {
                        Type dicType = dict[key].GetType();
                        dt.Columns[key].DataType = dicType.FullName == "System.DBNull" ? typeof (object) : dicType;
                    }
                }

                DataRow dr = dt.NewRow();

                foreach (string key in keys)
                {
                    dr[key] = dict[key];
                }

                dt.Rows.Add(dr);
            }

            InternalDataSource = dt;
        }
    }
}